﻿using Colorful.Furniture.Enum;
using Colorful.Furniture.ErpOrderManagement;
using Colorful.Furniture.Extensions;
using Microsoft.Extensions.Logging;
using System;
using System.Data;
using System.Drawing;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.DependencyInjection;
using Colorful.Furniture.ErpCustomerManagement;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using FreeSql;
using Colorful.Furniture.FinanceSdk;
using Dop.Core;
using System.Threading.Tasks;
using Volo.Abp;
using Colorful.Furniture.BasicDataManagement;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Colorful.Furniture.ResultManagement;
using Flurl.Http;
using System.Collections.Generic;
using StackExchange.Redis;


namespace Colorful.Furniture.BackgroundManagement;

/// <summary>
/// 推送充值状态信息-后台作业
/// </summary>
public class SentNotifyJob : BackgroundJob<SentNotifyArgs>, ISingletonDependency
{

    private readonly IFreeSql _freeSql;
    private readonly ILogger<SentNotifyArgs> _logger;
    private readonly IBaseRepository<RechargeOrderCallbackLog> _customerOrderCallbackLogRepository;
    private readonly IBackgroundJobManager _backgroundJobManager;
    private readonly FileConfig _fileConfig;
    private readonly IDatabase _redisDb;

    public SentNotifyJob(
        IBackgroundJobManager backgroundJobManager,
        IFreeSql freeSql,
        ILogger<SentNotifyArgs> logger,
        IBaseRepository<RechargeOrderCallbackLog> customerOrderCallbackLogRepository,
        IOptions<FileConfig> fileConfig,
        IConnectionMultiplexer connectionMultiplexer
    )
    {
        _backgroundJobManager = backgroundJobManager;
        _freeSql = freeSql;
        _logger = logger;
        _customerOrderCallbackLogRepository = customerOrderCallbackLogRepository;
        _fileConfig = fileConfig.Value;
        _redisDb = connectionMultiplexer.GetDatabase();
    }

    /// <summary>
    /// 执行推送客户提交的回调地址
    /// </summary>
    /// <param name="args"></param>
    public override async void Execute(SentNotifyArgs args)
    {
        // 暂停0.8秒
        await Task.Delay(800);

        var result = "";
        _logger.LogWarning($"执行客户地址回调 - 订单编号：{args.OrderNo}");
        var orderDownNo = args.OrderNo;
        using (var uow = _freeSql.CreateUnitOfWork())
        {
            uow.IsolationLevel = IsolationLevel.ReadUncommitted;
            //获取订单信息
            var orderInfo = _freeSql.Select<RechargeOrder>()
                .Where(x => x.OrderDownNo == orderDownNo)
                .DisableGlobalFilter("SoftDelete")
                .WithTransaction(uow.GetOrBeginTransaction())
                .ToOne();
            if (orderInfo == null)
            {
                _logger.LogWarning($"执行客户地址回调失败，无订单信息");
            }
            else
            {
                try
                {
                    if (orderInfo.Status == EnumOrderStatus.充值失败 || orderInfo.Status == EnumOrderStatus.充值成功)
                    {
                        //获取客户信息
                        var customerInfo = _freeSql.Select<Customer>()
                            .Where(x => x.Id == orderInfo.CustomerId)
                            .DisableGlobalFilter("SoftDelete")
                            .WithTransaction(uow.GetOrBeginTransaction())
                            .ToOne();

                        var status = orderInfo.Status == EnumOrderStatus.充值成功 ? "01" :
                            orderInfo.Status == EnumOrderStatus.充值中 ? "02" : "03";
                        var urlStr =
                            $"merchantId={customerInfo.Code}&outTradeNo={orderInfo.OutTradeNo}&rechargeAccount={orderInfo.RechargeAccount}&status={status}";
                        var signTemp = urlStr + "&key=" + customerInfo.Key;
                        var sign = Md5Encrypt.Md5Encrypt32(signTemp);
                        var remark = !string.IsNullOrEmpty(orderInfo.Remark)
                            ? orderInfo.Remark.Replace("，请联系客服协助处理", "")
                            : "";
                        var message = orderInfo.Status == EnumOrderStatus.充值中 ? "充值处理中" : remark;
                        var postData = urlStr + $"&message={message}&sign={sign}";

                        if (customerInfo.Code == 926170703) //拼多多店铺订单回调
                        {
                            var orderStatus = orderInfo.Status == EnumOrderStatus.充值成功 ? "SUCCESS" : orderInfo.Status == EnumOrderStatus.充值失败 ? "FAIL" : "ERROR";

                            await SentPddNotifyAsync(orderInfo.Id, orderStatus, orderInfo.OutTradeNo, orderInfo.OrderDownNo);
                        }
                        else //普通下游订单回调
                        {
                            //if (!string.IsNullOrEmpty(orderInfo.NotifyUrl))
                            //{
                            //    _logger.LogWarning($"进入--下单客户地址推送回调 - 订单编号：{orderDownNo}");

                            //    //提交
                            //    using (HttpClient client = new HttpClient())
                            //    {
                            //        using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                            //        {
                            //            try
                            //            {
                            //                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                            //                HttpResponseMessage response = client.PostAsync(orderInfo.NotifyUrl, httpContent).Result;
                            //                result = response.Content.ReadAsStringAsync().Result.CutSubstring(200);
                            //                _logger.LogWarning($"向客户回调推送成功-订单编号：{orderDownNo}，客户端返回内容：{result}");

                            //            }
                            //            catch (Exception e)
                            //            {
                            //                _logger.LogWarning($"向客户回调推送失败-订单编号：{orderDownNo}，客户端返回内容：{e.Message}");
                            //                result = e.Message.CutSubstring(300);
                            //            }
                            //        }
                            //    }
                            //}

                            ////写入回调信息
                            //var callbackLogInsert = new CustomerOrderCallbackLog()
                            //{
                            //    OrderId = orderInfo.Id,
                            //    OrderDownNo = orderInfo.OrderDownNo,
                            //    PostData = postData,
                            //    Result = result,
                            //    Status = orderInfo.Status,
                            //    Type = 2
                            //};

                            //_freeSql.Insert(callbackLogInsert)
                            //    .WithTransaction(uow.GetOrBeginTransaction())
                            //    .ExecuteAffrows();

                            ////回调不成功，且在3次回调内，再次执行回调
                            //if (result != "success")
                            //{
                            //    //获得总回调次数
                            //    var list = _freeSql.Select<CustomerOrderCallbackLog>()
                            //        .Where(x => x.OrderDownNo == orderInfo.OrderDownNo)
                            //        .WithTransaction(uow.GetOrBeginTransaction())
                            //        .Count(out var totalCount);

                            //    if (totalCount <= 3)
                            //    {
                            //        await _backgroundJobManager.EnqueueAsync(new SentNotifyUrlArgs
                            //        {
                            //            OrderDownNo = orderInfo.OrderDownNo
                            //        }, BackgroundJobPriority.Normal, TimeSpan.FromSeconds(30));
                            //    }
                            //}

                            ////判断是否有缓存订单信息
                            //var redisInfo = await _redisDb.StringGetAsync($"{_fileConfig.RedisName}:OrderSearch:{customerInfo.Code}:{orderInfo.OutTradeNo}");

                            //if (!redisInfo.HasValue)
                            //{
                            //    //插入缓存信息中
                            //    await _redisDb.StringSetAsync(
                            //        $"{_fileConfig.RedisName}:OrderSearch:{customerInfo.Code}:{orderInfo.OutTradeNo}",
                            //        JsonConvert.SerializeObject(new
                            //        {
                            //            status,
                            //            message,
                            //            outTradeNo = orderInfo.OutTradeNo,
                            //            rechargeAccount = orderInfo.RechargeAccount,
                            //            rechargeTime = Convert.ToDateTime(orderInfo.AddTime)
                            //                .ToString("yyyy-MM-dd HH:mm:ss"),
                            //            searchTime = Convert.ToDateTime(DateTime.Now)
                            //                .ToString("yyyy-MM-dd HH:mm:ss")
                            //        }), TimeSpan.FromHours(24));

                            //}
                        }
                    }
                    else
                    {
                        _logger.LogWarning($"回调失败 - 订单编号：{orderDownNo}，失败原因：订单还在充值中。");
                    }
                }
                catch (Exception e)
                {
                    await _backgroundJobManager.EnqueueAsync(new SentNotifyArgs
                    {
                        OrderNo = orderDownNo
                    }, BackgroundJobPriority.Normal, TimeSpan.FromSeconds(60));

                    _logger.LogWarning($"回调错误 - 订单编号：{orderDownNo}，错误原因：{e.Message}，60秒后再次进行回调");
                }
            }
            uow.Commit();
        }
    }



    /// <summary>
    /// 拼多多店铺订单回调
    /// </summary>
    /// <param name="id"></param>
    /// <param name="orderStatus">订单充值状态：0=充值成功；1=充值中；2=充值失败；</param>
    /// <param name="orderSn">拼多多订单号</param>
    /// <param name="orderDownNo">平台订单号</param>
    /// <returns></returns>
    public async Task<string> SentPddNotifyAsync(Guid id, string orderStatus, string orderSn, string orderDownNo)
    {
        _logger.LogWarning($"开始执行拼多多店铺回调 - 订单编号：{orderDownNo}");

        //获取订单提交时间
        var timeNow = DateTime.Now;

        var signStr = new SortedList<string, object>
        {
            {"type", "pdd.virtual.mobile.charge.notify"},
            {"client_id", "f4df955e3d434db9af7d0911ddf5a225"},
            {"access_token", "088b708344ce49fc97cf40073e4a1440cf47e50d"},
            {"timestamp", DateTimeExtensions.DateTimeToTimeStamp(timeNow)},
            {"data_type", "JSON"},
            {"ele_invoice", 0},
            {"order_sn", orderSn},
            {"outer_order_sn", orderDownNo},
            {"status", orderStatus}
        };
        StringBuilder builderSign = new StringBuilder();
        foreach (KeyValuePair<string, object> item in signStr)
        {
            var name = item.Key;
            var value = item.Value == null ? "" : item.Value.ToString();
            if (value != "")
            {
                builderSign.Append(name + value);
            }
        }

        var clientSecret = "d940c213db14ee22a8a0a09e20150019e314ab33";
        var signTemp = $"{clientSecret}{builderSign}{clientSecret}";
        // 大写加密
        var sign = Md5Encrypt.Md5Encrypt32(signTemp);

        var postStr = new SortedList<string, object>
        {
            {"type", "pdd.virtual.mobile.charge.notify"},
            {"client_id", "f4df955e3d434db9af7d0911ddf5a225"},
            {"access_token", "088b708344ce49fc97cf40073e4a1440cf47e50d"},
            {"timestamp", DateTimeExtensions.DateTimeToTimeStamp(timeNow)},
            {"data_type", "JSON"},
            {"ele_invoice", 0},
            {"order_sn", orderSn},
            {"outer_order_sn", orderDownNo},
            {"status", orderStatus},
            {"sign", sign},
        };
        StringBuilder builder = new StringBuilder();
        foreach (KeyValuePair<string, object> item in postStr)
        {
            var name = item.Key;
            var value = item.Value == null ? "" : item.Value.ToString();
            if (value != "")
            {
                builder.Append(name + "=" + value + "&");
            }
        }
        var postUrl = "http://gw-api.pinduoduo.com/api/router";
        var postQuery = builder.ToString().TrimEnd('&');

        try
        {
            var postResult = await postUrl.PostUrlEncodedAsync(postQuery).ReceiveJson<SuccessResultPddOutputDto>();

            if (postResult.mobile_charge_notify_response != null) //回调成功
            {
                _logger.LogWarning($"结束执行拼多多回调，回调响应成功 - 订单编号：{orderDownNo}，{orderSn}，" +
                                   $"回调结果：Status={postResult.mobile_charge_notify_response.success}");
                //写入回调信息
                var callbackLogInsert = new RechargeOrderCallbackLog()
                {
                    OrderId = new Guid(),
                    OrderNo = orderDownNo,
                    PostData = "",
                    Result = $"Status = {postResult.mobile_charge_notify_response.success}",
                    Type = 2
                };
                await _freeSql.Insert(callbackLogInsert)
                    .ExecuteAffrowsAsync();
            }
            else //回调失败
            {
                //写入回调信息
                var callbackLogInsert = new RechargeOrderCallbackLog()
                {
                    OrderId = id,
                    OrderNo = orderDownNo,
                    PostData = "",
                    Result = $"sub_msg={postResult.error_response.sub_msg}，error_msg={postResult.error_response.error_msg}",
                    Type = 2
                };
                await _freeSql.Insert(callbackLogInsert)
                    .ExecuteAffrowsAsync();

                _logger.LogWarning($"【推送充值信息失败】-【拼多多店铺】 - 订单编号：{orderDownNo}，{orderSn}，" +
                                   $"返回内容：sub_msg={postResult.error_response.sub_msg}，error_msg={postResult.error_response.error_msg}");
            }
            return $"success";
        }
        catch (Exception e)
        {
            _logger.LogWarning($"【推送充值信息失败】-【拼多多店铺】 - 订单编号：{orderDownNo}，{orderSn}，失败原因：{e.Message}");

            return $"{e.Message}";
        }

    }



}


public class SentNotifyArgs
{
    /// <summary>
    /// 平台订单号
    /// </summary>
    public string OrderNo { get; set; }

}


